<?php

namespace app\logic\single;

use app\api\model\order\OrderEntityApiModel;
use app\api\model\order\OrderEntityDetailApiModel;
use app\api\model\user\UserCouponApiModel;
use app\api\model\user\UserWriterWaterApiModel;
use think\facade\Db;

class OrderEntitySingle
{
    private static $inc;
    /**
     * @var OrderEntityApiModel
     */
    private $model;
    /**
     * @var OrderEntityDetailApiModel
     */
    private $orderDetailModel;
    /**
     * @var UserWriterWaterApiModel
     */
    private $userWriterWaterModel;

    private function __clone(){

    }
    // 禁止被实例化
    private function __construct()
    {
        $this->model = new OrderEntityApiModel();
        $this->orderDetailModel = new OrderEntityDetailApiModel();
        $this->userWriterWaterModel = new UserWriterWaterApiModel();
    }
    public static function getInstance(){
        if(is_null(self::$inc)){
            self::$inc = new self();
        }
        return self::$inc;
    }

    /**
     * 订单完成
     * @param string $order_id
     * @param int $pay_type
     * @return array
     */
    public function complete(string $order_id='',int $pay_type = 10,array $other = []): array
    {
        $order = $this->model->where('id',$order_id)->find();
        if(empty($order)){
            $order = $this->model->where('order_no',$order_id)->find();
        }
        if(empty($order)){
            return [-1,'订单不存在'];
        }
        if($order['status'] == 20){//如果已完成，则不能支付
            return [-1,'订单不能完成'];
        }
        Db::startTrans();
        try{
            $order_detail = $this->orderDetailModel->where('order_id',$order_id)->select();
            //修改订单状态
            $order->pay_type = $pay_type;
            $order->status = 20;
            $order->pay_time = date('Y-m-d H:i:s');
            if(isset($other['trade_no'])){
                $order->trade_no = $other['trade_no'];
            }
            $order->save();
            foreach ($order_detail as $val){
                $goods_id_arr[]=
                    [
                        'goods_id'=>$val['goods_id'],
                        'type'=>$val['type'],
                    ];
            }
            $goods_list = EntitySingle::getInstance()->getGoodsList($goods_id_arr);
            if($pay_type !=30){
                //给予积分
                UserScoreSingle::getInstance()->createLog($order['buyer_id'],1,$order['pay_price'],1,$order['id'],'购买订单获得积分:'.$order['pay_price']);
            }else{
                //扣除积分
                UserScoreSingle::getInstance()->createLog($order['buyer_id'],2,$order['pay_price'],100,$order['id'],'购买订单扣除积分:'.$order['pay_price']);
            }
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            return [-1,$exception->getMessage()];
        }
        return [1,'成功'];
    }



    public function cancle($id)
    {
        $order = $this->model->getFindById($id);
        if(empty($order)){
            return '订单不存在';
        }
        if($order['status'] != 10){
            return '该订单不能取消';
        }
        Db::startTrans();
        try{
            //修改运单状态
            $order->save(['status'=>-10,'cancel_time'=>date('Y-m-d H:i:s')]);
            //如果有优惠券，返还优惠券
            if(!empty($order['coupon_id'])){
                $user_coupon = UserCouponApiModel::where('id',$order['coupon_id'])->find();
                if(!empty($user_coupon)){
                    if($user_coupon['expire_time'] <= date('Y-m-d H:i:s')){
                        //过期了
                        $user_coupon->status = -1;
                    }else{
                        $user_coupon->status = 1;
                    }
                    $user_coupon->order_id = 0;
                    $user_coupon->save();
                }
            }
            Db::commit();
            return true;
        }catch (\Exception$exception){
            Db::rollback();
            return $exception->getMessage();
        }
    }
}